package com.jt.www.job.issue;

import com.jt.www.common.service.JobQueryListService;
import com.jt.www.dao.mapper.issue.mapper.IssuePolicyLogEntityMapper;
import com.jt.www.dao.mapper.issue.mapper.IssueRecordEntityMapper;
import com.jt.www.model.issue.entity.IssuePolicyLogEntity;
import com.jt.www.model.issue.entity.IssueRecordEntity;
import com.jt.www.util.DateUtils;
import com.jt.www.util.RedisUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.List;

/**
 * @Description: 消息表出单未处理电子批单
 * <p>
 * 循环处理消息表中消费状态为未处理（send_status = 1）并且是已出单的信息
 * 1.生成消息消费记录入库；
 * 2.更新消息表消费状态为消费成功（send_status = 2）；
 * @author: xuxinku
 * @Date: 2019/11/22 14:01
 * @ModifiedDate：
 * @Copyright:江泰保险股份有限公司
 */
@Component
@EnableScheduling
public class CheckPdIssueMQRecordTask implements SchedulingConfigurer {

    public static final Logger log = LoggerFactory.getLogger(CheckPdIssueMQRecordTask.class);
    /**
     * 单个服务器出单查询缓存失效时间 因不同的定时任务决定
     */
    private static final long ENDOR_MQ_TIME_OUT = 40L;
    /**
     * 检查 电子保单是否消费的定时任务 缓存key
     */
    private static final String ENDOR_MQ_LOCK_KEY = "EDU_ENDOR_ISSUE_MQ";
    @Autowired
    IssuePolicyLogEntityMapper issuePolicyLogEntityMapper;
    @Autowired
    IssueRecordEntityMapper issueRecordEntityMapper;
    @Autowired
    JobQueryListService jobQueryListService;
    /**
     * 任务开关
     */
    @Value("${jtpf.endormq.open}")
    private int checkOpen;
    /**
     * 任务执行周期
     */
    @Value("${jtpf.endormq.cron}")
    private String cron;// 每隔一分钟执行一次

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (checkOpen != 1) {
            return;
        }
        if (RedisUtil.setLock(ENDOR_MQ_LOCK_KEY, "1", ENDOR_MQ_TIME_OUT)) {
            Runnable task0 = () -> checkStart();
            Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
            taskRegistrar.addTriggerTask(task0, trigger0);
        }
    }

    private void checkStart() {
        String currentTime = DateUtils.getCurrentTime();
        log.info(currentTime + "CheckPdIssueMQRecordTask satrt,检查出单电子批单是否消费的任务开始...");

        Weekend<IssueRecordEntity> weekend = Weekend.of(IssueRecordEntity.class);
        WeekendCriteria<IssueRecordEntity, Object> criteria = weekend.weekendCriteria();
        criteria.andEqualTo(IssueRecordEntity::getSendStatus, "1");//1:未处理
        criteria.andLessThan(IssueRecordEntity::getStatus, "2");//只有成功的处理

        List<IssueRecordEntity> resultList = jobQueryListService.getJobProcessIssueRecordList(weekend);

        if (resultList != null && resultList.size() > 0) {

            for (IssueRecordEntity t : resultList) {

                String ifCode = t.getIfCode();

                switch (ifCode) {
                    case "20190516002":
                        //山东产品（临沂）
                        handleSD(t);
                        break;
                    default:
                        log.error("错误的批单ifCode {}", ifCode);
                }
            }

        }
        log.info(currentTime + "CheckPdIssueMQRecordTask end,检查出单电子批单是否消费的任务结束...");
    }


    /**
     * 山东产品（山东省校（园）方责任保险项目）
     *
     * @param t
     */
    private void handleSD(IssueRecordEntity t) {

        String currentTime = DateUtils.getCurrentTime();
        // 消费:从响应体中解析出 url，去调用数据中心的接口，下载电子批单
        IssuePolicyLogEntity issuePolicyLogEntity = new IssuePolicyLogEntity();
        String consumeStatus = "1";//未处理
        issuePolicyLogEntity.setApplicationFormCode(t.getApplicationFormCode());

        issuePolicyLogEntity.setPolicyNo(t.getPolicyNo());
        issuePolicyLogEntity.setType("2");//电子批单

        issuePolicyLogEntity.setStatus(consumeStatus);
        issuePolicyLogEntity.setCreateTime(currentTime);
        issuePolicyLogEntity.setUpdateTime(currentTime);
        issuePolicyLogEntity.setProCode(t.getProCode());
        String resPacket = t.getResPacket();
        log.info("检查mq消费记录的山东校责请求体是" + resPacket);
        String url = "";
        try {
            Document doc = DocumentHelper.parseText(resPacket);
            Element rootElement = doc.getRootElement();
            Element element = rootElement.element("body").element("apply");
            // 批单的信息
            if (element != null) {
                url = element.element("electricalDocument").getStringValue();
                // 拼装下载报文
                doc = DocumentHelper.createDocument();
                Element info = doc.addElement("body");
                info.addElement("url").addText(url);
                issuePolicyLogEntity.setParam(info.asXML());
                issuePolicyLogEntity.setTimes(0);
                issuePolicyLogEntity.setIfCode(t.getIfCode());
                issuePolicyLogEntityMapper.insert(issuePolicyLogEntity);
                // 只要消息进入消费记录的库，就认为消费成功，修改消息记录表状态,具体有没有成功 记录在消费记录表，有定时任务。
                t.setSendStatus("2");
                issueRecordEntityMapper.updateByPrimaryKeySelective(t);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }


}
